package com.jingdianjichi.subject.domain.handler.subject.factory;

import com.jingdianjichi.subject.common.enums.SubjectInfoTypeEnum;
import com.jingdianjichi.subject.domain.handler.subject.SubjectTypeHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目类型工厂,把我们的策略类加载进来
 *  /这时我们就省去的大量的if了
 */

/**
 * 使用工程去吐出去,不同的实现类,使用策略模式去处理不同的题目handler
 */
@Component
public class SubjectTypeHandlerFactory implements InitializingBean {

    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;        //这时他就会把四个策略类全部放进来了,利用Spring的特性来

    //装载工厂
    private Map<SubjectInfoTypeEnum,SubjectTypeHandler> handlerMap=new HashMap<>();

    //把Hander提供出去
    public SubjectTypeHandler getHandler(int subjectType){
        SubjectInfoTypeEnum typeEnum = SubjectInfoTypeEnum.getByCode(subjectType);

        return handlerMap.get(typeEnum);
    }


    //Spring的声明周期,去填充map集合
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubjectTypeHandler subjectTypeHandler : subjectTypeHandlerList) {
            handlerMap.put(subjectTypeHandler.getHandlerType(),subjectTypeHandler);
        }
    }
}
